package com.csap.framework.oauth2.server.service.admin.impl;

import cn.dev33.satoken.LoginUtil;
import com.csap.framework.oauth2.IUserDataCache;
import com.csap.framework.oauth2.request.UserRolesRequest;
import com.csap.framework.oauth2.server.model.UserRolesModel;
import com.csap.framework.oauth2.server.service.UserRolesService;
import com.csap.framework.oauth2.server.service.admin.AdminUserRoleService;
import com.csap.framework.redis.RedisUtil;
import com.csap.framework.util.Assert;
import com.csap.framework.util.StringUtil;
import lombok.Getter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 管理端 用户角色
 *
 * @Author ycf
 * @Date 2023/2/27 17:41
 * @Version 1.0
 */
@Service
public class AdminUserRoleServiceImpl implements AdminUserRoleService, IUserDataCache {
    @Resource
    private UserRolesService userRolesService;
    @Getter
    @Resource
    private RedisUtil redisUtil;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addUserRoles(UserRolesRequest roles, String userId) {
        if (Objects.nonNull(roles.getType())) {
            return addUserRoles(roles.getRoles(), roles.getType(), roles.getTypeId(), roles.getOpenId(), userId);
        }
        String openId = roles.getOpenId();
        userRolesService.removeByUserId(openId, userId);
        userRolesService.addUserRoles(userId, openId, LoginUtil.platform(), LoginUtil.clientId());
        userRolesService.addUserRoles(roles.getRoles(), openId, userId);
        clearUserRolePremissions(userId);
        return true;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public Boolean addUserRoles(Set<Long> roles, Integer type, String typeId, String openId, String userId) {
        userRolesService.removeByUserId(UserRolesModel.builder()
                .type(Assert.notNull(type, "类型不能为空"))
                .typeId(typeId)
                .openId(openId)
                .userId(userId)
                .build());
        boolean b = userRolesService.saveBatch(roles.stream().map(i -> UserRolesModel.builder()
                .roleId(i)
                .type(type)
                .typeId(typeId)
                .openId(openId)
                .userId(userId)
                .build()).collect(Collectors.toList()));
        clearUserRolePremissions(userId);
        return b;
    }


}
